const net = require('net')
const MyTransform = require('./myTransform.js')

let overageBuffer = null
let ts = new MyTransform()

const client = net.createConnection({
  port: 1234,
  host: 'localhost'
})

client.write(ts.encode('世界和平1'))
client.write(ts.encode('世界和平2'))
client.write(ts.encode('世界和平3'))
client.write(ts.encode('世界和平4'))

client.on('data', (chunk)=>{
  if(overageBuffer){
    // 非首次读取 连接chunk
    chunk = Buffer.concat([overageBuffer,chunk])
  }
  let packageLen = 0
  while(packageLen = ts.getPackageLen(chunk)){
    // 截取数据
    const packageCon = chunk.slice(0, packageLen)
    // 更新数据
    chunk = chunk.slice(packageLen)
    // 解码/拆包
    const ret = ts.decode(packageCon)
    console.log('拆包后数据',ret)
  }
  // 保存剩下没拿完的数据
  overageBuffer = chunk
})
